//
//  YZAvatarVM.m
//  VET
//
//  Created by Lam BG on 2018/7/4.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZAvatarVM.h"

#import "YZUser.h"

#import "YZSignAPI.h"
#import "YZUploadAPI.h"

#import "MJExtension.h"

@interface YZAvatarVM ()

@property (nonatomic, strong) YZSignAPI *inputUserInfoAPI;

@end

@implementation YZAvatarVM

- (instancetype)init {
    
    if (self = [super init]) {
        
        [self setup];
    }
    
    return self;
}

- (void)setup {
    
    @weakify(self)
    _nextSignal = [RACSignal combineLatest:@[RACObserve(self, userName), [RACObserve(self, isUploadComplete) distinctUntilChanged]] reduce:^id(NSString *userName, id isUploadComplete) {

        [self.inputUserInfoAPI addParam:@"id" value:[YZUser sharedInstance].uid];
        [self.inputUserInfoAPI addParam:@"name" value:userName];
        [self.inputUserInfoAPI addParam:@"nickname" value:userName];
        
        return @(userName.length && [isUploadComplete boolValue]);
    }];
    
    _nextCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            
            @strongify(self)
            [[self.inputUserInfoAPI putRequest] subscribeNext:^(NSDictionary *data) {
                
                [[YZUser sharedInstance] storeUserToLocal:data];
                [subscriber sendNext:data];
                [subscriber sendCompleted];

            } error:^(NSError * _Nullable error) {
                
                [subscriber sendError:error];
                [subscriber sendCompleted];
            }];
            
            return [RACDisposable disposableWithBlock:^{}];
        }];
    }];
}

- (RACSignal*)uploadSignal:(UIImage*)image withID:(NSString*)uid {
    
    // 上传图片
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        [[YZUploadAPI uploadImage:image imgPath:@"headImg" apiKey:@""] subscribeNext:^(NSDictionary *json) {
            
            // 上传中
            if (self.isUploadComplete) {
                
                self.isUploadComplete = NO;
            }
            [subscriber sendNext:json];
            
        } error:^(NSError * _Nullable error) {
            
            [subscriber sendError:error];
            [subscriber sendCompleted];
        } completed:^{
            
            // 上传完成
            self.isUploadComplete = YES;
            [subscriber sendCompleted];
        }];
        
        return [RACDisposable disposableWithBlock:^{}];
    }];
}

- (YZSignAPI *)inputUserInfoAPI {
    
    if (_inputUserInfoAPI == nil) {
        
        _inputUserInfoAPI = [YZSignAPI inputUserInfoAPI];
    }
    
    return _inputUserInfoAPI;
}


@end
